package com.insurance.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.insurance.domain.ResponseResult;
import com.insurance.domain.bo.CPatient;
import com.insurance.domain.entity.Customer;
import com.insurance.domain.entity.User;
import com.insurance.domain.enums.AppHttpCodeEnum;
import com.insurance.domain.vo.PageVo;
import com.insurance.domain.vo.UserInfoVo;
import com.insurance.domain.vo.UserPageVo;
import com.insurance.exception.SystemException;
import com.insurance.mapper.UserMapper;
import com.insurance.service.ChainConnectService;
import com.insurance.service.UserService;
import com.insurance.utils.BeanCopyUtils;
import com.insurance.utils.SecurityUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2023-03-28 15:16:23
 */
@Service("userService")
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private ChainConnectService chainConnectService;

    @Override
    public ResponseResult userInfo() {
        //获取用户id
        Long userId= SecurityUtils.getUserId();
        //获取用户信息
        User user=getById(userId);
        //将用户信息封装到vo类
        UserInfoVo vo= BeanCopyUtils.copyBean(user, UserInfoVo.class);
        return ResponseResult.okResult(vo);
    }

    @Override
    public ResponseResult updateUserInfo(User user) {
        updateById(user);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult register(User user) {
        //对数据进行非空判断
        if (!StringUtils.hasText(user.getUsername())) {
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        if (!StringUtils.hasText(user.getPassword())) {
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getRealName())){
            throw new SystemException(AppHttpCodeEnum.REALNAME_NOT_NULL);
        }
        //对数据进行是否存在的判断
        if (usernameExist(user.getUsername())) {
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if (nickNameExist(user.getNickName())) {
            throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
        }
        //TODO 还有一些判断 后期所有验证都使用验证框架validation
        //对密码进行加密
        String encodePassword = passwordEncoder.encode(user.getPassword());
        //存入数据库
        user.setPassword(encodePassword);
        save(user);
        CPatient cPatient = new CPatient(user.getUsername(), user.getRealName(), user.getGender().toString(), "", user.getDescription(), user.getAge().toString(), encodePassword);
        //区块链注册
        JSONObject result = chainConnectService.TYQX(cPatient);
        if(result==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.CHAINREGISTER_FAILED);
        }
        return ResponseResult.okResult("注册成功");
    }

    @Override
    public ResponseResult listByPage(UserPageVo userPageVo) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(!ObjectUtils.isEmpty(userPageVo.getRealName()),User::getRealName,userPageVo.getRealName());
        queryWrapper.eq(!ObjectUtils.isEmpty(userPageVo.getCountry()),User::getCountry,userPageVo.getCountry());
        queryWrapper.like(!ObjectUtils.isEmpty(userPageVo.getBirthPlace()),User::getBirthPlace,userPageVo.getBirthPlace());
        queryWrapper.like(!ObjectUtils.isEmpty(userPageVo.getPhone()), User::getPhone,userPageVo.getPhone());
        Page<User> page = new Page<>(userPageVo.getPageNo(), userPageVo.getPageSize());
        page(page,queryWrapper);
        List<User> users = page.getRecords();
        PageVo pageVo = new PageVo(users, page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult addUser(User user) {
        if(save(user)){
            return ResponseResult.okResult();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.ADD_FAILED);
    }

    @Override
    public ResponseResult updateUser(User user) {
        if(updateById(user)){
            return ResponseResult.okResult();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.UPDATE_ERROR);
    }

    //判断昵称是否存在
    private boolean nickNameExist(String nickName) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getNickName, nickName);
        return count(queryWrapper) > 0;
    }

    //判断用户名是否存在
    private boolean usernameExist(String userName) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, userName);
        return count(queryWrapper) > 0;
    }
}
